﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using K2.Listener.Entity;
using K2.Sync.Entity;
using K2.Sync.Service.Services;
using MongoDB.Driver;

namespace K2.Sync.Service.Handlers
{
    public class WorklistHandler
    {
        private static IMongoDatabase db = MongoFactory.GetDatabase();
        public void HandleWorklistMsg(WorklistListenerEntity msg)
        {
            switch (msg.ChangeType)
            {
                case 1:
                    DeleteWorklist(msg);
                    break;
                case 2:
                    InsertWorklist(msg);
                    break;
                default:
                    break;
            }
        }

        public void InsertWorklist(WorklistListenerEntity entity)
        {
            Console.WriteLine("Insert trigger!");
            //database.GetCollection<WorklistMongoEntity>("worklist").Database.DropCollection("worklist");
            K2DataService dataService = new K2DataService();
            var data = new WorklistMongoEntity
            {
                worklist = dataService.GetWorklistData(entity.ProcInstID)
            };
            db.GetCollection<WorklistMongoEntity>("worklist").InsertOne(data);
            var all = db.GetCollection<WorklistMongoEntity>("worklist").Find(x => x.worklist.ProcInstID != 0);
            Console.WriteLine(all.Count());
        }

        public void DeleteWorklist(WorklistListenerEntity entity)
        {
            Console.WriteLine("Delete trigger!");
            db.GetCollection<WorklistMongoEntity>("worklist").DeleteMany(x => x.worklist.CreateTime < entity.CreateTime && x.worklist.ProcInstID == entity.ProcInstID);
            var all = db.GetCollection<WorklistMongoEntity>("worklist").Find(x => x.worklist.ProcInstID != 0);
            Console.WriteLine(all.Count());
        }
    }
}
